package org.jeecgframework.web.material.controller;

import net.sf.json.JSONObject;

import org.jeecgframework.web.activiti.util.Variable;
<<<<<<< HEAD
=======
import org.jeecgframework.web.material.entity.OrderInfoEntity;
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
import org.jeecgframework.web.material.entity.OrderProcessEntity;
import org.jeecgframework.web.material.service.OrderFormServiceI;
import org.jeecgframework.web.material.service.OrderProcessServiceI;
import org.jeecgframework.web.material.page.OrderProcessPage;
import org.jeecgframework.web.material.entity.OrderFormEntity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Scope;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ManagementService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.core.util.MyBeanUtils;

/**
 * @Title: Controller
 * @Description: 订单流程
 * @author onlineGenerator
 * @date 2015-09-04 20:51:39
 * @version V1.0
 * 
 */
@Scope("prototype")
@Controller
@RequestMapping("/orderProcessController")
public class OrderProcessController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(OrderProcessController.class);

	@Autowired
	private OrderProcessServiceI orderProcessService;
	@Autowired
	private SystemService systemService;

	@Autowired
	private RuntimeService runtimeService;

	@Autowired
	protected TaskService taskService;

	@Autowired
	protected RepositoryService repositoryService;

	@Autowired
	private HistoryService historyService;

	@Autowired
	private ProcessEngine processEngine;
	
	@Autowired
	private OrderFormServiceI orderFormService;

	/**
	 * 订单流程列表 页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "orderProcess")
	public ModelAndView orderProcess(HttpServletRequest request) {
		return new ModelAndView("material/process/orderProcessList");
	}

	// /**
	// * easyui AJAX请求数据
	// *
	// * @param request
	// * @param response
	// * @param dataGrid
	// * @param user
	// */
	//
	// @RequestMapping(params = "datagrid")
	// public void datagrid(OrderProcessEntity orderProcess,HttpServletRequest
	// request, HttpServletResponse response, DataGrid dataGrid) {
	// CriteriaQuery cq = new CriteriaQuery(OrderProcessEntity.class, dataGrid);
	// //查询条件组装器
	// org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq,
	// orderProcess);
	// try{
	// //自定义追加查询条件
	// }catch (Exception e) {
	// throw new BusinessException(e.getMessage());
	// }
	// cq.add();
	// this.orderProcessService.getDataGridReturn(cq, true);
	// TagUtil.datagrid(response, dataGrid);
	// }

	/**
	 * easyui AJAX请求数据
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "datagrid")
	public void datagrid(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {

		ProcessDefinitionQuery query = repositoryService
				.createProcessDefinitionQuery();
		List<ProcessDefinition> list = query.list();

		request.getParameter("userName");
		request.getParameter("userAddress");
		StringBuffer rows = new StringBuffer();
		int i = 0;
		for (ProcessDefinition pi : list) {
			i++;
			rows.append("{'id':" + i + ",'processDefinitionId':'" + pi.getId()
					+ "','startPage':'" + pi.getDescription()
					+ "','resourceName':'" + pi.getResourceName()
					+ "','deploymentId':'" + pi.getDeploymentId() + "','key':'"
					+ pi.getKey() + "','name':'" + pi.getName()
					+ "','version':'" + pi.getVersion() + "','isSuspended':'"
					+ pi.isSuspended() + "'},");
		}
		String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

		JSONObject jObject = JSONObject.fromObject("{'total':" + query.count()
				+ ",'rows':[" + rowStr + "]}");
		responseDatagrid(response, jObject);
	}

	/**
	 * 删除订单流程
	 * 
	 * @return
	 */
	@RequestMapping(params = "doDel")
	@ResponseBody
	public AjaxJson doDel(OrderProcessEntity orderProcess,
			HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		orderProcess = systemService.getEntity(OrderProcessEntity.class,
				orderProcess.getId());
		String message = "订单流程删除成功";
		try {
			orderProcessService.delMain(orderProcess);
			systemService.addLog(message, Globals.Log_Type_DEL,
					Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "订单流程删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
<<<<<<< HEAD

=======
	
	
	/**
	 * 合并父订单查询.
	 * 
	 * @return
	 */
	@RequestMapping(params = "orderParentQuery")
	public ModelAndView orderParentQuery(HttpServletRequest request) {
		//设置编号
		String ids = request.getParameter("ids");
		request.setAttribute("ids", ids);
		return new ModelAndView("material/process/activityPage/selectOrder");
	}

	/**	
	 * easyui 合并父订单查询
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 * @param user
	 */

	@RequestMapping(params = "orderParentQueryDatagrid")
    public void orderParentQueryDatagrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		String ids = request.getParameter("ids");
		String[] idStr = ids.split(",");
		StringBuffer rows = new StringBuffer();
		int count = 0;
		for(String id : idStr){
			count = count+1;
			OrderProcessEntity order = orderProcessService.getEntity(OrderProcessEntity.class,  Integer.parseInt(id));
			ProcessInstance inst =  runtimeService.createProcessInstanceQuery().processInstanceId(order.getInstanceId()).active().singleResult();
			String name =orderProcessService.getProcessActivity().get(inst.getActivityId()).toString();
			rows.append("{'name':'"+name 
					+"','id':'"+order.getId()
					+"','orderCode':'"+order.getOrderProductId().getOrderId().getOrderCode()
					+"','userName':'"+order.getOrderProductId().getOrderId().getUserName()
					+"','userTelephone':'"+order.getOrderProductId().getOrderId().getUserTelephone1()
					+"','userAddress':'"+order.getOrderProductId().getOrderId().getUserAddress()
					+"','productName':'"+order.getOrderProductId().getProductId().getName()
					+"','productAmount':'"+order.getOrderProductId().getAmount()
					+"','isMerge':'"+order.getIsMerge()
					+"','productManufacturer':'"+order.getOrderProductId().getProductId().getManufacturer()+"'},");
			}
		String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");
		
		JSONObject jObject = JSONObject.fromObject("{'total':"+count+",'rows':["+rowStr+"]}");
		responseDatagrid(response, jObject);	
	}
	
	/**
	 * 批量删除订单流程
	 * 
	 * @return
	 */
	@RequestMapping(params = "orderMerge")
	@ResponseBody
	public AjaxJson orderMerge(String ids,String parentId ,HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "订单合并成功";
		try {
			orderProcessService.orderMerge(ids,parentId);
		} catch (Exception e) {
			e.printStackTrace();
			message = "订单合并失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
	
	/**
	 * 批量删除订单流程
	 * 
	 * @return
	 */
	@RequestMapping(params = "splitMerge")
	@ResponseBody
	public AjaxJson splitMerge(String ids,HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "订单拆分成功";
		try {
			orderProcessService.splitMerge(ids);
		} catch (Exception e) {
			e.printStackTrace();
			message = "订单拆分失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
	/**
	 * 批量删除订单流程
	 * 
	 * @return
	 */
	@RequestMapping(params = "doBatchDel")
	@ResponseBody
	public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "订单流程删除成功";
		try {
			for (String id : ids.split(",")) {
				OrderProcessEntity orderProcess = systemService.getEntity(
						OrderProcessEntity.class, Integer.parseInt(id));
				orderProcessService.delMain(orderProcess);
				systemService.addLog(message, Globals.Log_Type_DEL,
						Globals.Log_Leavel_INFO);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "订单流程删除失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 添加订单流程
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doAdd")
	@ResponseBody
	public AjaxJson doAdd(OrderProcessEntity orderProcess,
			OrderProcessPage orderProcessPage, HttpServletRequest request) {
		List<OrderFormEntity> orderFormList = orderProcessPage
				.getOrderFormList();
		AjaxJson j = new AjaxJson();
		String message = "添加成功";
		try {
			orderProcessService.addMain(orderProcess, orderFormList);
			systemService.addLog(message, Globals.Log_Type_INSERT,
					Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "订单流程添加失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 更新订单流程
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "doUpdate")
	@ResponseBody
	public AjaxJson doUpdate(OrderProcessEntity orderProcess,
			OrderProcessPage orderProcessPage, HttpServletRequest request) {
		List<OrderFormEntity> orderFormList = orderProcessPage
				.getOrderFormList();
		AjaxJson j = new AjaxJson();
		String message = "更新成功";
		try {
			orderProcessService.updateMain(orderProcess, orderFormList);
			systemService.addLog(message, Globals.Log_Type_UPDATE,
					Globals.Log_Leavel_INFO);
		} catch (Exception e) {
			e.printStackTrace();
			message = "更新订单流程失败";
			throw new BusinessException(e.getMessage());
		}
		j.setMsg(message);
		return j;
	}

	/**
	 * 订单流程新增页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goAdd")
	public ModelAndView goAdd(OrderProcessEntity orderProcess,
			HttpServletRequest req) {
		if (StringUtil.isNotEmpty(orderProcess.getId())) {
			orderProcess = orderProcessService.getEntity(
					OrderProcessEntity.class, orderProcess.getId());
			req.setAttribute("orderProcessPage", orderProcess);
		}
		return new ModelAndView("material/process/orderProcess-add");
	}

	/**
	 * 订单流程编辑页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "goUpdate")
	public ModelAndView goUpdate(OrderProcessEntity orderProcess,
			HttpServletRequest req) {
		if (StringUtil.isNotEmpty(orderProcess.getId())) {
			orderProcess = orderProcessService.getEntity(
					OrderProcessEntity.class, orderProcess.getId());
			req.setAttribute("orderProcessPage", orderProcess);
		}
		return new ModelAndView("material/process/orderProcess-update");
	}

	/**
	 * 加载明细列表[xdkj]
	 * 
	 * @return
	 */
	@RequestMapping(params = "orderFormList")
	public ModelAndView orderFormList(OrderProcessEntity orderProcess,
			HttpServletRequest req) {

		// ===================================================================================
		// 获取参数
		Object id0 = orderProcess.getId();
		// ===================================================================================
		// 查询-xdkj
		String hql0 = "from OrderFormEntity where 1 = 1 AND oRDER_PROCESS_ID = ? ";
		try {
			List<OrderFormEntity> orderFormEntityList = systemService.findHql(
					hql0, id0);
			req.setAttribute("orderFormList", orderFormEntityList);
		} catch (Exception e) {
			logger.info(e.getMessage());
		}
		return new ModelAndView("material/process/orderFormList");
	}

	/**
	 * 请假流程启动
	 * 
	 * @param deploymentId
	 *            流程部署ID
	 */
	@RequestMapping(params = "orderProcessStart")
	@ResponseBody
	public AjaxJson orderProcessStart(OrderProcessEntity process,
			HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		// 当前用户
		TSUser user = ResourceUtil.getSessionUserName();
		process.setAssignedId("admin");

		OrderProcessEntity order = new OrderProcessEntity();
		order.setAssignedId(user.getId());
		order.setAssignedName(user.getUserName());
		order.setAssignedTel(user.getMobilePhone());
		// 请假流程启动
		orderProcessService.processWorkFlowStart(order);

		String message = "流程启动成功";
		j.setMsg(message);
		return j;
	}

	/**
	 * 完成任务表单选择
	 */
	@RequestMapping(params = "taskCompletePageSelect")
	public ModelAndView taskCompletePageSelect(
			@RequestParam("jspPage") String jspPage,
			@RequestParam("processInstanceId") String processInstanceId,
			@RequestParam("taskId") String taskId, HttpServletRequest request,
			Model model) {

		ProcessInstance processInstance = runtimeService
				.createProcessInstanceQuery()
				.processInstanceId(processInstanceId).active().singleResult();

		String businessKey = processInstance.getBusinessKey();

		OrderProcessEntity leave = orderProcessService
				.getOrderProcess(new Integer(businessKey));

		model.addAttribute("processInstanceId", processInstanceId);
		model.addAttribute("taskId", taskId);
		model.addAttribute("leave", leave);

		System.out.println(jspPage);

		return new ModelAndView("material/process/activityPage/"
				+ jspPage.substring(0, jspPage.lastIndexOf(".")));
	}

	/**
	 * 完成任务
	 * 
	 * @param deploymentId
	 *            流程部署ID
	 */
	@RequestMapping(params = "completeTask")
	@ResponseBody
	public AjaxJson completeTask(String taskId, Variable var,
			HttpServletRequest request,OrderFormEntity form) {
		//执行任务
	    orderProcessService.completeTask(taskId, var,form);
		// 当前用户
		TSUser user = ResourceUtil.getSessionUserName();
		AjaxJson j = new AjaxJson();

		String message = "办理成功";
		j.setMsg(message);
		return j;
	}

	/**
	 * easyui 待领任务页面
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "waitingClaimTask")
	public ModelAndView waitingClaimTask() {

		return new ModelAndView("material/process/waitingClaimTask");
	}

	/**
	 * easyui AJAX请求数据 待领任务
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "waitingClaimTaskDataGrid")
	public void waitingClaimTaskDataGrid(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {
		TSUser user = ResourceUtil.getSessionUserName();
		String userId = user.getId();
		TaskService taskService = processEngine.getTaskService();
		List<Task> tasks = taskService.createTaskQuery()
				.taskCandidateUser(userId).active().list();// .taskCandidateGroup("deptLeader").active().list();

		StringBuffer rows = new StringBuffer();
		for (Task t : tasks) {
			String processInstanceId =  t.getProcessInstanceId();
			ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
			
			String businessKey = processInstance.getBusinessKey();
			OrderProcessEntity order = orderProcessService.getEntity(OrderProcessEntity.class,  Integer.parseInt(businessKey));
<<<<<<< HEAD
			rows.append("{'name':'"+t.getName() +"','description':'"+t.getDescription()+"','taskId':'"+t.getId()+"','processDefinitionId':'"+t.getProcessDefinitionId()
			+"','processInstanceId':'"+t.getProcessInstanceId()
			+"','orderCode':'"+order.getOrderProductId().getOrderId().getOrderCode()
			+"','userName':'"+order.getOrderProductId().getOrderId().getUserName()
			+"','userTelephone':'"+order.getOrderProductId().getOrderId().getUserTelephone1()
			+"','userAddress':'"+order.getOrderProductId().getOrderId().getUserAddress()
			+"','productName':'"+order.getOrderProductId().getProductId().getName()
			+"','productAmount':'"+order.getOrderProductId().getAmount()
			+"','productManufacturer':'"+order.getOrderProductId().getProductId().getManufacturer()+"'},");
=======
			if(order!=null&&!"true".equals(order.getIsMerge())){

				rows.append("{'name':'"+t.getName() +"','description':'"+t.getDescription()+"','taskId':'"+t.getId()+"','processDefinitionId':'"+t.getProcessDefinitionId()
				+"','processInstanceId':'"+t.getProcessInstanceId()
				+"','orderCode':'"+order.getOrderProductId().getOrderId().getOrderCode()
				+"','userName':'"+order.getOrderProductId().getOrderId().getUserName()
				+"','userTelephone':'"+order.getOrderProductId().getOrderId().getUserTelephone1()
				+"','userAddress':'"+order.getOrderProductId().getOrderId().getUserAddress()
				+"','productName':'"+order.getOrderProductId().getProductId().getName()
				+"','productAmount':'"+order.getOrderProductId().getAmount()
				+"','productManufacturer':'"+order.getOrderProductId().getProductId().getManufacturer()+"'},");
			
			}
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
		}
		String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

		JSONObject jObject = JSONObject.fromObject("{'total':" + tasks.size()
				+ ",'rows':[" + rowStr + "]}");
		responseDatagrid(response, jObject);
	}

	/**
	 * easyui 待办任务页面
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "claimedTask")
	public ModelAndView claimedTask() {

		return new ModelAndView("material/process/claimedTask");
	}
	
	/**
	 * easyui 待办任务页面
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "deleteProcessInstance")
	public ModelAndView deleteProcessInstance() {

		runtimeService.deleteProcessInstance("13201", "正常删除");
		runtimeService.deleteProcessInstance("16301", "正常删除");
		runtimeService.deleteProcessInstance("16317", "正常删除");
		return new ModelAndView("material/process/claimedTask");
	}
	
	

	/**
	 * easyui AJAX请求数据 待办任务
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "claimedTaskDataGrid")
	public void claimedTaskDataGrid(HttpServletRequest request, HttpServletResponse response, DataGrid dataGrid) {
		
		TSUser user = ResourceUtil.getSessionUserName();
		String userId = user.getId();
		TaskService taskService = processEngine.getTaskService();
        List<Task> tasks = taskService.createTaskQuery().taskAssignee(userId).list();
        String userName = request.getParameter("userName")==null?"":request.getParameter("userName").toString();
        String userAddress = request.getParameter("userAddress")==null?"":request.getParameter("userAddress").toString();
        String userTelephone = request.getParameter("userTelephone")==null?"":request.getParameter("userTelephone");
        String productName = request.getParameter("productName")==null?"":request.getParameter("productName");
        String name = request.getParameter("name")==null?"":request.getParameter("name");
		StringBuffer rows = new StringBuffer();
		for(Task t : tasks){
			String processInstanceId =  t.getProcessInstanceId();
			ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
			
			String businessKey = processInstance.getBusinessKey();
			OrderProcessEntity order = orderProcessService.getEntity(OrderProcessEntity.class,  Integer.parseInt(businessKey));
			if(order !=null
			   &&order.getOrderProductId().getOrderId().getUserName().contains(userName)
			   &&order.getOrderProductId().getOrderId().getUserAddress().contains(userAddress)
			   &&order.getOrderProductId().getOrderId().getUserTelephone1().contains(userTelephone)
			   &&order.getOrderProductId().getProductId().getName().contains(productName)
			   &&t.getName().contains(name)){
			
			rows.append("{'name':'"+t.getName() +"','description':'"+t.getDescription()+"','taskId':'"+t.getId()+"','processDefinitionId':'"+t.getProcessDefinitionId()
			+"','processInstanceId':'"+t.getProcessInstanceId()
<<<<<<< HEAD
			+"','orderCode':'"+order.getOrderProductId().getOrderId().getOrderCode()
=======
			+"','id':'"+order.getId()
			+"','orderCode':'"+order.getOrderProductId().getOrderId().getOrderCode()
			+"','isMerge':'"+order.getIsMerge()
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
			+"','userName':'"+order.getOrderProductId().getOrderId().getUserName()
			+"','userTelephone':'"+order.getOrderProductId().getOrderId().getUserTelephone1()
			+"','userAddress':'"+order.getOrderProductId().getOrderId().getUserAddress()
			+"','productName':'"+order.getOrderProductId().getProductId().getName()
			+"','productAmount':'"+order.getOrderProductId().getAmount()
			+"','productManufacturer':'"+order.getOrderProductId().getProductId().getManufacturer()+"'},");
			}
		}
		String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");
		
		JSONObject jObject = JSONObject.fromObject("{'total':"+tasks.size()+",'rows':["+rowStr+"]}");
		responseDatagrid(response, jObject);
	}

	/**
	 * easyui 已办任务页面
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "finishedTask")
	public ModelAndView finishedTask() {

		return new ModelAndView("material/process/finishedTask");
	}

	/**
	 * easyui AJAX请求数据 已办任务
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */
	@RequestMapping(params = "finishedTaskDataGrid")
	public void finishedTask(HttpServletRequest request,
			HttpServletResponse response, DataGrid dataGrid) {

		TSUser user = ResourceUtil.getSessionUserName();
		String userId = user.getId();
		List<HistoricTaskInstance> historicTasks = historyService
				.createHistoricTaskInstanceQuery().taskAssignee(userId)
				.finished().list();

		StringBuffer rows = new StringBuffer();
		for (HistoricTaskInstance t : historicTasks) {
			String processInstanceId =  t.getProcessInstanceId();
			ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).active().singleResult();
			
			String businessKey = processInstance.getBusinessKey();
			OrderProcessEntity order = orderProcessService.getEntity(OrderProcessEntity.class,  Integer.parseInt(businessKey));
			rows.append("{'name':'"+t.getName() +"','description':'"+t.getDescription()+"','taskId':'"+t.getId()+"','processDefinitionId':'"+t.getProcessDefinitionId()
			+"','processInstanceId':'"+t.getProcessInstanceId()
			+"','orderCode':'"+order.getOrderProductId().getOrderId().getOrderCode()
			+"','userName':'"+order.getOrderProductId().getOrderId().getUserName()
			+"','userTelephone':'"+order.getOrderProductId().getOrderId().getUserTelephone1()
			+"','userAddress':'"+order.getOrderProductId().getOrderId().getUserAddress()
			+"','productName':'"+order.getOrderProductId().getProductId().getName()
			+"','productAmount':'"+order.getOrderProductId().getAmount()
			+"','productManufacturer':'"+order.getOrderProductId().getProductId().getManufacturer()+"'},");
		}
		String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

		JSONObject jObject = JSONObject.fromObject("{'total':"
				+ historicTasks.size() + ",'rows':[" + rowStr + "]}");
		responseDatagrid(response, jObject);
	}

	/**
	 * 签收任务
	 * 
	 * @param taskId
	 */
	@RequestMapping(params = "claimTask")
	@ResponseBody
	public AjaxJson claimTask(@RequestParam("taskId") String taskId,
			HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
<<<<<<< HEAD

		TSUser user = ResourceUtil.getSessionUserName();
		String userId = user.getId();

		TaskService taskService = processEngine.getTaskService();
		// 获取当前任务
		Task task = taskService.createTaskQuery()
				.taskId(taskId).singleResult();
		taskService.claim(taskId, userId);
		
        //签收后更新待办人信息
		ProcessInstance instance =runtimeService.createProcessInstanceQuery()
				.processInstanceId(task.getProcessInstanceId()).active().singleResult();
		
		if(instance!=null){
			OrderProcessEntity process = orderProcessService.getEntity(OrderProcessEntity.class
					, Integer.parseInt(instance.getBusinessKey()));
			//设置待办人信息
			process.setAssignedId(user.getId());
			process.setAssignedName(user.getUserName());
			process.setAssignedTel(user.getMobilePhone());
			//保存待办人信息
			orderProcessService.saveOrUpdate(process);
		}
=======
        //任务签收
		orderProcessService.claim(taskId);
>>>>>>> a9c7731b4788b28c37d962faa7843e2cac438e61
		
		String message = "签收成功";
		j.setMsg(message);
		return j;
	}

	/**
	 * easyui 流程历史页面
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "viewProcessInstanceHistory")
	public ModelAndView viewProcessInstanceHistory(
			@RequestParam("processInstanceId") String processInstanceId,
			HttpServletRequest request, HttpServletResponse respone, Model model) {

		model.addAttribute("processInstanceId", processInstanceId);

		return new ModelAndView("activiti/process/viewProcessInstanceHistory");
	}

	/**
	 * easyui 流程历史数据获取
	 * 
	 * @param request
	 * @param response
	 * @param dataGrid
	 */

	@RequestMapping(params = "taskHistoryList")
	public void taskHistoryList(
			@RequestParam("processInstanceId") String processInstanceId,
			HttpServletRequest request, HttpServletResponse response,
			DataGrid dataGrid) {

		List<HistoricTaskInstance> historicTasks = historyService
				.createHistoricTaskInstanceQuery()
				.processInstanceId(processInstanceId).list();

		StringBuffer rows = new StringBuffer();
		for (HistoricTaskInstance hi : historicTasks) {
			rows.append("{'name':'" + hi.getName() + "','processInstanceId':'"
					+ hi.getProcessInstanceId() + "','startTime':'"
					+ hi.getStartTime() + "','endTime':'" + hi.getEndTime()
					+ "','assignee':'" + hi.getAssignee()
					+ "','deleteReason':'" + hi.getDeleteReason() + "'},");
			// System.out.println(hi.getName()+"@"+hi.getAssignee()+"@"+hi.getStartTime()+"@"+hi.getEndTime());
		}

		String rowStr = StringUtils.substringBeforeLast(rows.toString(), ",");

		JSONObject jObject = JSONObject.fromObject("{'total':"
				+ historicTasks.size() + ",'rows':[" + rowStr + "]}");
		responseDatagrid(response, jObject);
	}

	// -----------------------------------------------------------------------------------
	// 以下各函数可以提成共用部件 (Add by Quainty)
	// -----------------------------------------------------------------------------------
	public void responseDatagrid(HttpServletResponse response,
			JSONObject jObject) {
		response.setContentType("application/json");
		response.setHeader("Cache-Control", "no-store");
		try {
			PrintWriter pw = response.getWriter();
			pw.write(jObject.toString());
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
